<?php
declare (strict_types = 1);

namespace app\live\model;

use app\api\model\WxApi;
use think\Model;

/**
 * @mixin \think\Model
 */
class LiveBroadcastRelation extends Model
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错
    public $rekey = '';


    /*
     * 添加记录
     */
    public function add($id,$goods,$time)
    {
        try{
            if(empty($id['uid'])||empty($id['live_id'])) exception('用户/房间不能为空!');
            if(empty($goods)||!is_array($goods)) exception('商品id不能为空!');
            if(empty($time['start'])||empty($time['end'])) exception('开始/结束时间不能为空!');
            $goodsInfo = (new LiveBroadcastGoods())->field('wx_goods_id,goods_id')->where('goods_id','in',$goods)->select()->toArray();
            $goodsArr = [];
            foreach($goodsInfo as $k=>$v){ $goodsArr[$v['goods_id']] = $v['wx_goods_id']; }
            $model = new LiveBroadcastGoods();
            $redis = getRedis();
            $list = [];
            foreach($goods as $k=>$v){
                if(!empty($v)){
                    $wxgoods = isset($goodsArr[$v]) ? $goodsArr[$v] : 0;
                    $list[] = ['live_broadcast_id'=>$id['live_id'], 'wx_goods_id'=>$wxgoods, 'goods_id'=>$v];
                }
            }
            if(!empty($list)){
                if(!$this->insertAll($list)) exception('添加商品失败!');
                else{
                    $wx_goods = array_column($list,'wx_goods_id');
                    $api = new WxApi();
                    $ret['room_id'] = $id['room_id'];
                    $ret['uid'] = $id['uid'];
                    $ret['goods'] = $wx_goods;
                    $req = $api->addGoods($ret);
                    if($req == false) exception('添加商品到直播间失败!');
                    /*foreach($list as $v){
                        $delInfo = $redis->hDel($model->rekey.date('Ymd').'_'.$v['goods_id'],$time['start'].'-'.$time['end']);
                    }*/
                    $redis->hDel($model->rekey.$id['uid'],$time['start'].'-'.$time['end']);
                    return true;
                }
            }else exception('添加商品错误，请重新添加!');
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
}
